<template>
  <div>
    <el-card>
      <el-input style="width: 200px" placeholder="请输入..." v-model="name"></el-input>
      <el-button style="margin-left: 10px" type="success" @click="load" plain>查询</el-button>
      <el-button type="info" @click="reset" plain>重置</el-button>
      <el-button plain type="primary" @click="handleAdd">新增</el-button>
    </el-card>

    <el-card style="margin: 10px 0">
        <el-table style="margin: 10px 0" :data="tableData" stripe :header-cell-style="{background:'aliceblue',color:'#666'}"  >
          <el-table-column prop="id" label="序号" width="70" align="center" >
            <template slot-scope='scope'>
              <span>{{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="姓名"></el-table-column>
      <el-table-column align="center" prop="content" label="介绍">
        <template slot-scope="scope">
          <el-button plain type="success" @click="view(scope.row)" size="mini">预览</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="growth" label="生平"></el-table-column>
          <el-table-column align="center" prop="state" label="事迹"></el-table-column>
          <el-table-column align="center" prop="works" label="代表作品"></el-table-column>
          <el-table-column align="center" label="图片"><template v-slot="scope"><el-image style="width: 100px; height: 100px" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image></template></el-table-column>
          <el-table-column align="center" prop="type.name" label="分类"></el-table-column>
          <el-table-column align="center" prop="user" label="发布人"></el-table-column>
      <el-table-column align="center" prop="time" label="发布时间"></el-table-column>

          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini">编辑</el-button>
              <el-button plain type="danger" size="mini" @click=del(scope.row.id)>删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin: 10px 0">
          <el-pagination
              style="padding: 0"
              background
              layout="total, prev, pager, next"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-size="pageSize"
              :total="total">
          </el-pagination>
        </div>
    </el-card>


    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
      <el-form label-width="100px" style="padding-right: 40px" :model="form" :rules="rules" ref="ruleForm">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="介绍">
          <div id="editor"></div>
        </el-form-item>
        <el-form-item prop="growth" label="生平">
          <el-input v-model="form.growth" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="state" label="事迹">
          <el-input v-model="form.state" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="works" label="代表作品">
          <el-input v-model="form.works" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="img" label="图片">
          <el-upload :action="$baseUrl +'/file/upload'" :headers="{ token: user.token }" ref="img" :on-success="handleImgUploadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="typeId" label="分类">
          <el-select v-model="form.typeId" placeholder="请选择">
            <el-option
                v-for="item in types"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="信息" :visible.sync="dialogFormVisible1" width="60%">
      <div class="w-e-text" v-html="content"></div>
    </el-dialog>
  </div>
</template>

<script>
import E from "wangeditor"

export default {
  name: "Item",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: '10',
      name: "",
      form: {},
      dialogFormVisible: false,
      dialogFormVisible1: false,
      editor: null,
      content: '',
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      rules: {
        name: [
          { required: true, message: '请输入必填项', trigger: 'blur'}
        ],
      },
      types: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    setEditor() {
      this.$nextTick(() => {
        this.editor = new E(`#editor`)
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgServer = 'http://localhost:9090/file/editor/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadVideoServer = 'http://localhost:9090/file/editor/uploadVideo'
        this.editor.config.uploadVideoName = 'file'
        this.editor.config.uploadVideoHeaders = {
          token: this.user.token
        }
        this.editor.create()
      })
    },
    view(row) {
      this.content = row.content
      this.dialogFormVisible1 = true
    },
    destroy() {
      this.editor.destroy()
      this.editor = null
    },
    load() {
      this.$request.get("/item/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: 10,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data?.records
        this.total = res.data?.total
      })

      this.$request.get("/type").then(res => {
        this.types = res.data
      })
    },
    save() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.form.content = this.editor.txt.html()
           this.$request({
             method: this.form.id ? 'PUT' : 'POST',
             url: "/item",
             data: this.form
           }).then(res => {
              if (res.code === '200') {
                this.$message.success("操作成功")
                this.dialogFormVisible = false
                this.load()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
      this.$nextTick(() => {
        // 设置富文本
        this.setEditor()
        this.destroy()

        if(this.$refs.img) {
           this.$refs.img.clearFiles();
         }
         if(this.$refs.file) {
          this.$refs.file.clearFiles();
         }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
       this.$nextTick(() => {
         // 设置富文本
         this.setEditor()
         setTimeout(() => {
           this.editor.txt.html(row.content) //设置内容
         }, 0)
         this.destroy()

         if(this.$refs.img) {
           this.$refs.img.clearFiles();
         }
         if(this.$refs.file) {
          this.$refs.file.clearFiles();
         }
       })
    },
    del(id) {
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
       this.$request.delete("/item/" + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.load()
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {})
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    handleFileUploadSuccess(res) {
      this.form.file = res.data
    },
    handleImgUploadSuccess(res) {
      this.form.img = res.data
    }
  }
}
</script>


<style scope>

</style>
